<!DOCTYPE html>


<html lang="zh-CN">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="welcome" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    ThreadLocal |  ChenyyのBlog
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">
  
<link rel="stylesheet" href="/css/custom.css">

  
  <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-Java/ThreadLocal"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  ThreadLocal
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2021/05/20/Java/ThreadLocal/" class="article-date">
  <time datetime="2021-05-20T12:21:58.000Z" itemprop="datePublished">2021-05-20</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.5k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">9 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <ul>
<li>简介</li>
<li>使用</li>
<li>原理</li>
<li>应用场景</li>
<li>内存泄漏</li>
</ul>
<span id="more"></span>

<h1 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h1><p>多线程访问同一个共享变量的时候容易出现并发问题，ThreadLocal是除了加锁外的一种规避多线程不安全的方法。</p>
<p>ThreadLocal是JDK包提供的，它提供线程本地变量，每个线程都会有变量的一个副本，访问的都是线程自己的变量副本，从而规避了线程安全问题，如下图所示</p>
<p><img src="https://img2018.cnblogs.com/blog/1368768/201906/1368768-20190613220434628-1803630402.png" alt="img"></p>
<h1 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h1><ul>
<li><p>void set(Object value)：设置当前线程的线程局部变量的值。</p>
</li>
<li><p>public Object get()该方法返回当前线程所对应的线程局部变量。</p>
</li>
<li><p>public void remove()：将当前线程局部变量的值删除，线程结束后局部变量将自动被垃圾回收，为了避免内存泄漏，建议使用完调用。</p>
</li>
<li><p>protected Object initialValue()：返回该线程局部变量的初始值，在线程第1次调用get()或set(Object)时才延迟执行，且仅执行1次。</p>
</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">public class ThreadLocalTest &#123;</span><br><span class="line"></span><br><span class="line">    static ThreadLocal&lt;String&gt; localVar = new ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    static void print(String str) &#123;</span><br><span class="line">        //打印当前线程中本地内存中本地变量的值</span><br><span class="line">        System.out.println(str + &quot; :&quot; + localVar.get());</span><br><span class="line">        //清除本地内存中的本地变量</span><br><span class="line">        localVar.remove();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        Thread t1  = new Thread(new Runnable() &#123;</span><br><span class="line">            @Override</span><br><span class="line">            public void run() &#123;</span><br><span class="line">                //设置线程1中本地变量的值</span><br><span class="line">                localVar.set(&quot;localVar1&quot;);</span><br><span class="line">                //调用打印方法</span><br><span class="line">                print(&quot;thread1&quot;);</span><br><span class="line">                //打印本地变量</span><br><span class="line">                System.out.println(&quot;after remove : &quot; + localVar.get());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        Thread t2  = new Thread(new Runnable() &#123;</span><br><span class="line">            @Override</span><br><span class="line">            public void run() &#123;</span><br><span class="line">                //设置线程2中本地变量的值</span><br><span class="line">                localVar.set(&quot;localVar2&quot;);</span><br><span class="line">                //调用打印方法</span><br><span class="line">                print(&quot;thread2&quot;);</span><br><span class="line">                //打印本地变量</span><br><span class="line">                System.out.println(&quot;after remove : &quot; + localVar.get());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        </span><br><span class="line">        // thread1 :localVar1</span><br><span class="line">        // after remove : null</span><br><span class="line">        // thread2 :localVar2</span><br><span class="line">        // after remove : null</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h1><p>1）每个Thread线程内部都维护了一个ThreadLocalMap</p>
<p>2）Map里面储存线程本地对象key（threadLocal）和线程的变量副本value（存储的对象）。</p>
<p>3）Thread内部的Map是由ThreadLocal维护的，由ThreadLocal负责向Map获取和设置线程的变量值</p>
<p>这样对于不同的线程，每次获取副本值时，别的线程并不能获取到当前线程的副本值，这样就形成了副本隔离，互不干扰.</p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210524192133.png"></p>
<h2 id="ThreadLocal-get"><a href="#ThreadLocal-get" class="headerlink" title="ThreadLocal.get():"></a>ThreadLocal.get():</h2><p>1.获取当前线程的ThreadLocalMap对象threadLocals（实际储存副本值的Map）</p>
<p>2.Map不为空的话，从Map中获取线程储存的K-V Entry结点，然后从Entry结点中获取Value副本值返回</p>
<p>3.Map为空的话，返回初始值null，之后还需向Map中添加value为null的键值对，避免空指针异常</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">public T get() &#123;</span><br><span class="line">    Thread t = Thread.currentThread();</span><br><span class="line">    ThreadLocalMap map = getMap(t);</span><br><span class="line">    if (map != null) &#123;</span><br><span class="line">        ThreadLocalMap.Entry e = map.getEntry(this);</span><br><span class="line">        if (e != null)</span><br><span class="line">            return (T)e.value;</span><br><span class="line">    &#125;</span><br><span class="line">    return setInitialValue();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ThreadLocalMap getMap(Thread t) &#123;</span><br><span class="line">    return t.threadLocals;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">private T setInitialValue() &#123;</span><br><span class="line">    T value = initialValue();</span><br><span class="line">    Thread t = Thread.currentThread();</span><br><span class="line">    ThreadLocalMap map = getMap(t);</span><br><span class="line">    if (map != null)</span><br><span class="line">        map.set(this, value);</span><br><span class="line">    else</span><br><span class="line">        createMap(t, value);</span><br><span class="line">    return value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">protected T initialValue() &#123;</span><br><span class="line">    return null;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="ThreadLocal-set"><a href="#ThreadLocal-set" class="headerlink" title="ThreadLocal.set():"></a>ThreadLocal.set():</h2><p>1.获取当前线程的成员变量Map</p>
<p>2.Map不为空：重新将ThreadLocal对象和Value副本放入Map中</p>
<p>3.Map为空：对线程成员变量ThreadLocalMap进行初始化创建，并将ThreadLocal对象和Value副本放入Map中</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public void set(T value) &#123;</span><br><span class="line">    Thread t = Thread.currentThread();</span><br><span class="line">    ThreadLocalMap map = getMap(t);</span><br><span class="line">    if (map != null)</span><br><span class="line">        map.set(this, value);</span><br><span class="line">    else</span><br><span class="line">        createMap(t, value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">ThreadLocalMap getMap(Thread t) &#123;</span><br><span class="line">    return t.threadLocals;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">void createMap(Thread t, T firstValue) &#123;</span><br><span class="line">    t.threadLocals = new ThreadLocalMap(this, firstValue);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="ThreadLocalMap-set"><a href="#ThreadLocalMap-set" class="headerlink" title="ThreadLocalMap.set()"></a>ThreadLocalMap.set()</h2><p>1.先是计算槽位</p>
<p>2.Entry数组中存在需要插入的key，直接替换即可，存在key=null，也是替换（可以避免value内存泄漏）</p>
<p>3.Entry数组中不存在需要插入的key，也没有key=null，新增一个Entry，然后判断一下需不需要扩容和清除过期的值（关于扩容和清除过期值先不细讲）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">//Entry为ThreadLocalMap静态内部类，对ThreadLocal的若引用</span><br><span class="line">//同时让ThreadLocal和储值形成key-value的关系</span><br><span class="line">static class Entry extends WeakReference&lt;ThreadLocal&lt;?&gt;&gt; &#123;</span><br><span class="line">    /** The value associated with this ThreadLocal. */</span><br><span class="line">    Object value;</span><br><span class="line"></span><br><span class="line">    Entry(ThreadLocal&lt;?&gt; k, Object v) &#123;</span><br><span class="line">           super(k);</span><br><span class="line">            value = v;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//ThreadLocalMap构造方法</span><br><span class="line">ThreadLocalMap(ThreadLocal&lt;?&gt; firstKey, Object firstValue) &#123;</span><br><span class="line">        //内部成员数组，INITIAL_CAPACITY值为16的常量</span><br><span class="line">        table = new Entry[INITIAL_CAPACITY];</span><br><span class="line">        //位运算，结果与取模相同，计算出需要存放的位置</span><br><span class="line">        //threadLocalHashCode比较有趣</span><br><span class="line">        int i = firstKey.threadLocalHashCode &amp; (INITIAL_CAPACITY - 1);</span><br><span class="line">        table[i] = new Entry(firstKey, firstValue);</span><br><span class="line">        size = 1;</span><br><span class="line">        setThreshold(INITIAL_CAPACITY);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>实例化ThreadLocalMap时创建了一个长度为16的Entry数组。每个线程Thread持有一个ThreadLocalMap类型的实例threadLocals，可以理解成每个线程Thread都持有一个Entry型的数组table。</p>
<p>通过hashCode与length位运算确定出一个索引值i，这个i就是被存储在table数组中的位置。</p>
<h2 id="ThreadLocal"><a href="#ThreadLocal" class="headerlink" title="ThreadLocal"></a>ThreadLocal</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">//在某一线程声明了ABC三种类型的ThreadLocal</span><br><span class="line">ThreadLocal&lt;A&gt; sThreadLocalA = new ThreadLocal&lt;A&gt;();</span><br><span class="line">ThreadLocal&lt;B&gt; sThreadLocalB = new ThreadLocal&lt;B&gt;();</span><br><span class="line">ThreadLocal&lt;C&gt; sThreadLocalC = new ThreadLocal&lt;C&gt;();</span><br></pre></td></tr></table></figure>

<p>一个Thread来说只有持有一个ThreadLocalMap，所以ABC三个ThreadLocal对应同一个ThreadLocalMap对象。</p>
<p>为了管理ABC，通过将threadLocal的hashCode进行位运算(取模)得到索引i，将ABC存储在一个数组的不同位置，而这个数组就是上面提到的Entry型的数组table。</p>
<p>总结如下：</p>
<ol>
<li>对于某一ThreadLocal来讲，他的索引值i是确定的，在不同线程之间访问时访问的是不同的table数组的同一位置即都为table[i]，只不过这个不同线程之间的table是独立的。</li>
<li>对于同一线程的不同ThreadLocal来讲，这些ThreadLocal实例共享一个table数组，然后每个ThreadLocal实例在table中的索引i是不同的。</li>
</ol>
<h1 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h1><h3 id="保存每个线程独享的对象"><a href="#保存每个线程独享的对象" class="headerlink" title="保存每个线程独享的对象"></a>保存每个线程独享的对象</h3><p>ThreadLocal 用作保存每个线程独享的对象，为每个线程都创建一个副本，这样每个线程都可以修改自己所拥有的副本, 而不会影响其他线程的副本，确保了线程安全。</p>
<h3 id="保存线程内用户信息"><a href="#保存线程内用户信息" class="headerlink" title="保存线程内用户信息"></a>保存线程内用户信息</h3><p>ThreadLocal 用作每个线程内需要独立保存信息，以便供其他方法更方便地获取该信息的场景。每个线程获取到的信息可能都是不一样的，前面执行的方法保存了信息后，后续方法可以通过ThreadLocal 直接获取到，避免了传参，类似于全局变量的概念。</p>
<p>例如，用 ThreadLocal 保存一些业务内容（用户权限信息、从用户系统获取到的用户名、用户ID 等），这些信息在同一个线程内相同，但是不同的线程使用的业务内容是不相同的。</p>
<p>在线程生命周期内，都通过这个静态 ThreadLocal 实例的 get() 方法取得自己 set 过的那个对象，避免了将这个对象（如 user 对象）作为参数传递的麻烦。</p>
<h2 id="避免线程内多次获取数据库连接、Session-管理等"><a href="#避免线程内多次获取数据库连接、Session-管理等" class="headerlink" title="避免线程内多次获取数据库连接、Session 管理等"></a>避免线程内多次获取数据库连接、Session 管理等</h2><p><strong>在数据库连接上的应用</strong></p>
<p><img src="https://gitee.com/chenyy-2017/pic/raw/master/note/20210520211942.png"></p>
<h2 id="ThreadLocal和Synchronized区别"><a href="#ThreadLocal和Synchronized区别" class="headerlink" title="ThreadLocal和Synchronized区别"></a>ThreadLocal和Synchronized区别</h2><ul>
<li>Synchronized是通过线程等待，牺牲时间来解决访问冲突</li>
<li>ThreadLocal是通过每个线程单独一份存储空间，牺牲空间来解决冲突，并且相比于Synchronized，ThreadLocal具有线程隔离的效果，只有在线程内才能获取到对应的值，线程外则不能访问到想要的值。</li>
</ul>
<h1 id="ThreadLocal导致内存泄漏"><a href="#ThreadLocal导致内存泄漏" class="headerlink" title="ThreadLocal导致内存泄漏"></a>ThreadLocal导致内存泄漏</h1><p>内存溢出: Memory overflow <strong>没有足够的内存</strong>提供申请者使用.</p>
<p><strong>内存泄漏</strong>: Memory Leak 程序中<strong>已经动态分配的堆内存</strong>由于某种原因， <strong>程序未释放或者无法释放， 造成系统内部的浪费</strong>， 导致程序运行速度减缓甚至系统崩溃等严重结果。内存泄漏的堆积终将导致内存溢出。</p>
<h2 id="key-ThreadLocal是强引用行不行？"><a href="#key-ThreadLocal是强引用行不行？" class="headerlink" title="key=ThreadLocal是强引用行不行？"></a>key=ThreadLocal是强引用行不行？</h2><p>假设在业务代码中使用完ThreadLocal， ThreadLocal ref被回收了。</p>
<p>但是因为threadLocalMap的Entry强引用了threadLocal(key就是threadLocal)，造成ThreadLocal无法被回收。</p>
<p>在没有手动删除Entry以及CurrentThread(当前线程)依然运行的前提下， 始终有强引用链CurrentThread Ref → CurrentThread →Map(ThreadLocalMap)-&gt; entry， Entry就不会被回收( Entry中包括了ThreadLocal实例和value)，导致Entry内存泄漏。</p>
<h2 id="key-ThreadLocal是弱引用还会内存泄漏吗"><a href="#key-ThreadLocal是弱引用还会内存泄漏吗" class="headerlink" title="key=ThreadLocal是弱引用还会内存泄漏吗"></a>key=ThreadLocal是弱引用还会内存泄漏吗</h2><p>假设在业务代码中使用完ThreadLocal， ThreadLocal ref被回收了。</p>
<p>由于threadLocalMap只持有ThreadLocal的弱引用，没有任何强引用指向threadlocal实例（这里Entry不再强引用ThreadLocal了）， 所以threadlocal就可以顺利被gc回收， 此时Entry中的key = null。</p>
<p>在没有手动删除Entry以及CurrentThread依然运行的前提下，也存在始终有强引用链CurrentThread Ref → CurrentThread →Map(ThreadLocalMap)-&gt; entry,value就不会被回收，而这块value永远不会被访问到了（因为key=null），导致value内存泄漏。</p>
<h2 id="为什么-key-要用弱引用"><a href="#为什么-key-要用弱引用" class="headerlink" title="为什么 key 要用弱引用"></a>为什么 key 要用弱引用</h2><p>两种内存泄漏的情况中．都有两个前提：</p>
<p>1 . 没有手动侧除这个 Entry</p>
<p>2 . CurrentThread 当前线程依然运行</p>
<p>综上， ThreadLocal 内存泄漏的根源是：</p>
<p>由于ThreadLocalMap 的生命周期跟 Thread 一样长，如果没有手动删除（remove()方法）对应 key 就会导致内存泄漏。</p>
<p><strong>要避免内存泄漏有两种方式：</strong></p>
<ul>
<li> 1 ．使用完 ThreadLocal ，调用其 remove 方法删除对应的 Entry</li>
<li> 2 ．使用完 ThreadLocal ，当前 Thread 也随之运行结束</li>
</ul>
<p><strong>那么为什么 key 要用弱引用呢</strong></p>
<p>事实上，在 ThreadLocalMap 中的set/getEntry 方法中，会对 key 为 null（也即是 ThreadLocal 为 null ）进行判断，如果为 null 的话，那么会把 value 置为 null 的。</p>
<p> 这就意味着使用完 ThreadLocal，CurrentThread 依然运行的前提下。就算忘记调用 remove 方法，弱引用比强引用可以多一层保障：弱引用的 ThreadLocal 会被回收。对应value在下一次 ThreadLocaIMap 调用 set/get/remove 中的任一方法的时候会被清除，从而避免内存泄漏。</p>
<p>参考：</p>
<p>ThreadLocal：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/3c5d7f09dfbd">https://www.jianshu.com/p/3c5d7f09dfbd</a></p>
<p>Java中的ThreadLocal详解：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/fsmly/p/11020641.html">https://www.cnblogs.com/fsmly/p/11020641.html</a></p>
<p>深入源码理解ThreadLocal和ThreadLocalMap:<a target="_blank" rel="noopener" href="https://www.cnblogs.com/yinbiao/p/10728909.html">https://www.cnblogs.com/yinbiao/p/10728909.html</a></p>
<p>ThreadLocal 内存泄露问题：<a target="_blank" rel="noopener" href="https://blog.csdn.net/JH39456194/article/details/107304997">https://blog.csdn.net/JH39456194/article/details/107304997</a></p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          打赏
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2021/05/20/Java/ThreadLocal/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java/" rel="tag">Java</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2021/05/21/Mysql/MVCC%E5%A4%9A%E7%89%88%E6%9C%AC%E5%B9%B6%E5%8F%91%E6%8E%A7%E5%88%B6/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            MVCC多版本并发控制
          
        </div>
      </a>
    
    
      <a href="/2021/05/16/blog/markmap-Markdown%E8%BD%AC%E6%80%9D%E7%BB%B4%E5%AF%BC%E5%9B%BE/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">markmap：Markdown转思维导图</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2021
        <i class="ri-heart-fill heart_icon"></i> Chenyy
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>访问人数:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>浏览次数:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="ChenyyのBlog"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">文章</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/book">收藏</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about/me">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="搜索">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>